let isSelecting = false;
let currentXPath = '';
let lastSelectedTreeItem = null;

 
 

// 初始化按钮事件监听
document.addEventListener('DOMContentLoaded', () => {
    const selectButton = document.getElementById('select-button');
    const copyXPathButton = document.getElementById('copy-xpath');

    selectButton.addEventListener('click', () => {
        const newState = !isSelecting;
        updateSelectButtonState(newState);
        
        // 通知content script切换选择模式
        chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
            chrome.tabs.sendMessage(tabs[0].id, {
                type: 'toggleSelect',
                enabled: newState
            });
        });
    });

    copyXPathButton.addEventListener('click', () => {
        if (currentXPath) {
            copyToClipboard(currentXPath);
            showNotification('已复制XPath到剪贴板！');
        }
    });

    // 在面板加载完成后请求更新树结构
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
        chrome.tabs.sendMessage(tabs[0].id, {
            type: 'requestTreeUpdate'
        });
    });
});

// 复制到剪贴板
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).catch(err => {
        console.error('复制失败:', err);
    });
}

// 显示通知
function showNotification(message) {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 12px;
        right: 12px;
        background-color: #4CAF50;
        color: white;
        padding: 8px 16px;
        border-radius: 4px;
        z-index: 10000;
        font-size: 14px;
    `;
    notification.textContent = message;
    document.body.appendChild(notification);
    setTimeout(() => notification.remove(), 2000);
}

// 更新选择按钮状态
function updateSelectButtonState(selecting) {
    const selectButton = document.getElementById('select-button');
    isSelecting = selecting;
    selectButton.textContent = selecting ? '停止选择' : '开始选择';
    selectButton.classList.toggle('active', selecting);
    
}

// 与content script通信
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'updatePreview') {
        updatePreview(message.xpath, message.text, message.html);
    } else if (message.type === 'updateTree') {
        updateTree(message.treeHtml);
    } else if (message.type === 'selectionStopped' && !lastTreeSelection) {
        // 只有在非树形结构选择时才更新按钮状态
        updateSelectButtonState(false);
    }
});

let lastTreeSelection = false;

function updatePreview(xpath, text, html) {
    currentXPath = xpath || '';
    document.getElementById('xpath-content').textContent = xpath || '';
    document.getElementById('text-content').textContent = text || '';
    
    // 更新 HTML 预览，使用 innerText 来显示 HTML 代码
    const htmlContent = document.getElementById('html-content');
    if (htmlContent && html) {
        // 对 HTML 进行格式化处理
        const formattedHtml = html
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
        htmlContent.innerHTML = `<pre style="margin: 0; white-space: pre-wrap;">${formattedHtml}</pre>`;
    } else if (htmlContent) {
        htmlContent.textContent = '';
    }

    // 更新树形结构...
    const treeItem = findTreeItemByXPath(xpath);
    if (treeItem) {
        expandToTreeItem(treeItem);
        scrollTreeItemIntoView(treeItem);
    }
}

function updateTree(treeHtml) {
    const treeContainer = document.getElementById('xpath-tree');
    if (!treeHtml) return;
    
    // 清空现有内容并添加新的树结构
    treeContainer.innerHTML = treeHtml;
    
    // 为第一级节点添加展开状态
    const rootItems = treeContainer.children;
    if (rootItems.length > 0) {
        const firstItem = rootItems[0];
        const indent = firstItem.querySelector('.tree-indent');
        if (indent) {
            indent.style.display = 'block';
            const expandButton = firstItem.querySelector('.tree-expand');
            if (expandButton) {
                expandButton.textContent = '▼';
            }
        }
    }
    
    addTreeEventListeners();
}

function addTreeEventListeners() {
    const treeItems = document.querySelectorAll('.tree-item');
    treeItems.forEach(item => {
        // 点击展开/折叠图标
        const expandButton = item.querySelector('.tree-expand');
        if (expandButton) {
            expandButton.addEventListener('click', (e) => {
                e.stopPropagation();
                const content = item.querySelector('.tree-indent');
                if (content) {
                    const isExpanded = content.style.display !== 'none';
                    content.style.display = isExpanded ? 'none' : 'block';
                    expandButton.textContent = isExpanded ? '▶' : '▼';
                }
            });
        }
        
        // 点击元素行
        item.addEventListener('click', (e) => {
            e.stopPropagation();
            // 如果点击的是展开/折叠按钮，不处理选择逻辑
            if (e.target.classList.contains('tree-expand')) {
                return;
            }

            const xpath = item.dataset.xpath;
            if (xpath) {
                // 更新 xpath 显示
                currentXPath = xpath;
                document.getElementById('xpath-content').textContent = xpath;

                // 高亮当前点击的项
                if (lastSelectedTreeItem) {
                    lastSelectedTreeItem.classList.remove('highlight');
                }
                item.classList.add('highlight');
                lastSelectedTreeItem = item;

                // 标记这是从树形结构的选择
                lastTreeSelection = true;
                
                // 通知 content script 选中元素
                chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                    chrome.tabs.sendMessage(tabs[0].id, {
                        type: 'selectTreeElement',
                        xpath: xpath
                    });
                });
                // 100ms 后重置标记
                setTimeout(() => {
                    lastTreeSelection = false;
                }, 100);
            }
        });
    });
}

// 根据XPath查找树节点
function findTreeItemByXPath(xpath) {
    return document.querySelector(`.tree-item[data-xpath="${xpath}"]`);
}

// 展开到指定树节点
function expandToTreeItem(treeItem) {
    // 移除之前选中节点的高亮
    if (lastSelectedTreeItem) {
        lastSelectedTreeItem.classList.remove('highlight');
    }
    
    // 高亮当前节点
    treeItem.classList.add('highlight');
    lastSelectedTreeItem = treeItem;
    
    // 展开所有父节点
    let current = treeItem;
    while (current) {
        const parentTreeItem = current.parentElement.closest('.tree-item');
        if (parentTreeItem) {
            const indent = parentTreeItem.querySelector('.tree-indent');
            if (indent) {
                indent.style.display = 'block';
                const expandButton = parentTreeItem.querySelector('.tree-expand');
                if (expandButton) {
                    expandButton.textContent = '▼';
                }
            }
        }
        current = parentTreeItem;
    }
}

// 将树节点滚动到可视区域
function scrollTreeItemIntoView(treeItem) {
    const treeContainer = document.getElementById('xpath-tree');
    const itemRect = treeItem.getBoundingClientRect();
    const containerRect = treeContainer.getBoundingClientRect();
    
    if (itemRect.top < containerRect.top || itemRect.bottom > containerRect.bottom) {
        treeItem.scrollIntoView({
            behavior: 'smooth',
            block: 'center'
        });
    }
}

